package com.webber.demo.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * properties 工具类，处理加载properties文件
 * 
 * @author mhl
 *
 */
public class PropertiesUtil {
	
	public static Map<String, Properties> properties = new HashMap<String, Properties>();
	
	/**
	 * 加载属性文件并存入Map
	 * @param fileName
	 * @return
	 * @throws IOException 
	 */
	private static Properties load(String fileName) throws IOException {
		Properties p = new Properties();
		InputStream in = null;
		try {
			in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
			p.load(in);
			properties.put(fileName, p);
			return p;
		} catch (IOException e) {
			throw new IOException();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {

				}
			}
		}
	}

	/**
	 * 读取属性值，先从内存中取。
	 * @param fileName
	 * @param key
	 * @return
	 * @throws IOException
	 */
	public static String getValue(String fileName, String key) throws IOException{
		Properties p = properties.get(fileName);
		if(p==null)
			p = load(fileName);
		return p.getProperty(key);
	}
	
	/**
	 * 如果文件更新，则更新内存.
	 */
	public static void reload()
	{
		properties = new HashMap<String, Properties>();
	}
}
